// 教员信息及考勤页面脚本
(function(){
    // API_BASE变量已废弃，所有调用应使用相对路径

    // 页面初始化
    document.addEventListener('DOMContentLoaded', ()=>{
        console.log('教员信息及考勤页面初始化开始...');
        initUser();
        initProfile();
        bindLogout();
        bindMenu(); // 添加菜单绑定
        console.log('教员信息及考勤页面初始化完成');
    });

    // 初始化用户信息
    function initUser(){
        const userInfo = JSON.parse(localStorage.getItem('userInfo')||'{}');
        
        // 检查用户是否已登录
        if (!userInfo.token || !userInfo.userDTO) {
            console.log('用户未登录，跳转到登录页');
            window.location.href = 'login.html';
            return;
        }
        
        // 获取用户信息
        const userDTO = userInfo.userDTO;
        const name = userDTO.nickName || userDTO.account || '教师';
        const avatar = userDTO.icon || '';
        
        // 显示用户姓名
        document.getElementById('teacher-name').textContent = name;
        
        // 显示用户头像
        const avatarElement = document.getElementById('user-avatar');
        if (avatarElement) {
            if (avatar) {
                avatarElement.src = avatar;
                avatarElement.alt = name + '的头像';
            } else {
                // 如果没有头像，显示默认头像（使用用户名首字母）
                avatarElement.src = '';
                avatarElement.style.background = 'linear-gradient(135deg, #667eea, #764ba2)';
                avatarElement.style.display = 'flex';
                avatarElement.style.alignItems = 'center';
                avatarElement.style.justifyContent = 'center';
                avatarElement.style.color = 'white';
                avatarElement.style.fontWeight = 'bold';
                avatarElement.style.fontSize = '14px';
                avatarElement.textContent = name.charAt(0).toUpperCase();
                avatarElement.alt = name + '的头像';
            }
        }
        
        console.log('用户信息加载成功:', { name, avatar, permission: userDTO.permission });
    }

    // 初始化教员信息及考勤
    function initProfile(){
        // 设置当前月份
        const now = new Date();
        const currentMonth = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
        document.getElementById('attendanceMonth').value = currentMonth;
        
        // 绑定刷新考勤按钮
        document.getElementById('refreshAttendance').addEventListener('click', loadAttendance);
        
        // 初始加载教员信息
        loadProfile();
    }

    // 加载教员信息
    function loadProfile(){
        const userInfo = JSON.parse(localStorage.getItem('userInfo')||'{}');
        if (!userInfo.userDTO) return;
        
        const userDTO = userInfo.userDTO;
        
        // 显示个人信息
        document.getElementById('profile-name').textContent = userDTO.nickName || '未设置';
        document.getElementById('profile-account').textContent = `T${String(userDTO.id).padStart(4, '0')}`; // 生成教师编号
        document.getElementById('profile-permission').textContent = getPermissionText(userDTO.permission);
        
        // 设置创建时间为当前时间（模拟）
        const now = new Date();
        const createTime = new Date(now.getFullYear() - 2, now.getMonth(), now.getDate()); // 假设2年前入职
        document.getElementById('profile-create-time').textContent = createTime.toLocaleDateString('zh-CN');
        
        // 显示头像
        const profileAvatar = document.getElementById('profile-avatar');
        if (userDTO.icon && userDTO.icon.trim() !== '') {
            profileAvatar.src = userDTO.icon;
            profileAvatar.style.display = 'block';
            profileAvatar.style.background = 'none';
            profileAvatar.textContent = '';
        } else {
            // 默认头像 - 使用用户名首字母
            profileAvatar.src = '';
            profileAvatar.style.background = 'linear-gradient(135deg, #667eea, #764ba2)';
            profileAvatar.style.display = 'flex';
            profileAvatar.style.alignItems = 'center';
            profileAvatar.style.justifyContent = 'center';
            profileAvatar.style.color = 'white';
            profileAvatar.style.fontWeight = 'bold';
            profileAvatar.style.fontSize = '48px';
            profileAvatar.textContent = (userDTO.nickName || '教').charAt(0).toUpperCase();
        }
        
        // 加载考勤记录
        loadAttendance();
        
        console.log('教员信息加载成功:', userDTO);
    }

    // 获取权限文本
    function getPermissionText(permission) {
        switch(permission) {
            case 0: return '普通教师';
            case 1: return '班主任';
            case 2: return '年级主任';
            case 3: return '教务主任';
            case 4: return '管理员';
            default: return '未知';
        }
    }

    // 加载考勤记录
    async function loadAttendance(){
        const month = document.getElementById('attendanceMonth').value;
        const tbody = document.getElementById('attendanceBody');
        const empty = document.getElementById('attendanceEmpty');
        
        tbody.innerHTML = '';
        empty.style.display = 'none';
        
        try {
            // 这里使用占位API，待后端实现后替换
            // 假设接口：GET /teacher/attendance?month=yyyy-MM
            // const res = await fetch(`${API_BASE}/teacher/attendance?month=${month}`);
            // const list = res.data || [];
            
            // 临时模拟数据
            const list = generateMockAttendanceData(month);
            
            if(!list.length) {
                empty.style.display = 'block';
                return;
            }
            
            // 统计考勤数据
            const stats = {
                total: list.length,
                normal: 0,
                late: 0,
                absent: 0
            };
            
            for(const item of list) {
                // 统计各种状态的数量
                stats[item.status]++;
                
                // 获取星期
                const date = new Date(item.date);
                const weekDay = getWeekDayText(date.getDay());
                
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${item.date}</td>
                    <td>${weekDay}</td>
                    <td>${item.checkIn}</td>
                    <td>${item.checkOut}</td>
                    <td>${item.workHours}</td>
                    <td><span class="attendance-status status-${item.status}">${getStatusText(item.status)}</span></td>
                `;
                tbody.appendChild(tr);
            }
            
            // 更新统计信息
            updateAttendanceStats(stats);
            
        } catch(err) {
            empty.style.display = 'block';
            empty.textContent = '加载考勤记录失败，请稍后重试';
            console.error(err);
        }
    }

    // 生成模拟考勤数据
    function generateMockAttendanceData(month) {
        const [year, monthNum] = month.split('-').map(Number);
        const daysInMonth = new Date(year, monthNum, 0).getDate();
        const data = [];
        
        for(let day = 1; day <= daysInMonth; day++) {
            const date = new Date(year, monthNum - 1, day);
            const dayOfWeek = date.getDay();
            
            // 跳过周末
            if(dayOfWeek === 0 || dayOfWeek === 6) continue;
            
            // 更真实的考勤数据生成
            let status, checkIn, checkOut, workHours;
            const random = Math.random();
            
            if (random > 0.85) {
                // 15% 概率迟到
                status = 'late';
                checkIn = '08:30';
                checkOut = '17:00';
                workHours = '8.5小时';
            } else if (random > 0.95) {
                // 10% 概率缺勤
                status = 'absent';
                checkIn = '-';
                checkOut = '-';
                workHours = '-';
            } else {
                // 75% 概率正常
                status = 'normal';
                checkIn = '08:00';
                checkOut = '17:00';
                workHours = '9小时';
            }
            
            // 添加一些特殊日期处理
            const dayOfMonth = date.getDate();
            if (dayOfMonth === 1) {
                // 月初第一天，通常是正常
                status = 'normal';
                checkIn = '08:00';
                checkOut = '17:00';
                workHours = '9小时';
            }
            
            data.push({
                date: `${year}-${String(monthNum).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
                checkIn,
                checkOut,
                workHours,
                status
            });
        }
        
        return data;
    }

    // 获取状态文本
    function getStatusText(status) {
        switch(status) {
            case 'normal': return '正常';
            case 'late': return '迟到';
            case 'absent': return '缺勤';
            default: return '未知';
        }
    }

    // 获取星期文本
    function getWeekDayText(day) {
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return weekDays[day];
    }

    // 更新考勤统计
    function updateAttendanceStats(stats) {
        document.getElementById('total-days').textContent = stats.total;
        document.getElementById('normal-days').textContent = stats.normal;
        document.getElementById('late-days').textContent = stats.late;
        document.getElementById('absent-days').textContent = stats.absent;
    }

    // 绑定退出登录
    function bindLogout(){
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            console.log('找到退出登录按钮，绑定点击事件');
            logoutBtn.addEventListener('click', function(e) {
                console.log('退出登录按钮被点击');
                e.preventDefault();
                logout();
            });
            console.log('退出登录按钮事件绑定完成');
        } else {
            console.error('未找到退出登录按钮！');
        }
    }

    // 退出登录
    async function logout(){
        console.log('=== 退出登录开始 ===');
        try {
            // 显示加载状态
            const logoutBtn = document.getElementById('logoutBtn');
            if (!logoutBtn) {
                console.error('未找到退出登录按钮！');
                return;
            }
            
            logoutBtn.disabled = true;
            logoutBtn.textContent = '退出中...';
            console.log('按钮状态已更新为加载中');
            
            // 获取用户token
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            const token = userInfo.token;
            console.log('从localStorage获取的用户信息:', userInfo);
            console.log('获取到的token:', token);
            
            if (!token) {
                console.log('没有token，直接清除本地数据并跳转');
                clearUserDataAndRedirect();
                return;
            }
            
            console.log('准备调用后端退出登录接口:', '/user/logout');

            // 调用后端退出登录接口
            const response = await fetch('/user/logout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                }
            });
            
            console.log('收到响应:', response);
            console.log('响应状态:', response.status);
            
            if (response.ok) {
                const result = await response.json();
                console.log('响应内容:', result);
                if (result.success) {
                    console.log('退出登录成功');
                    clearUserDataAndRedirect();
                } else {
                    console.error('退出登录失败:', result.errorMsg);
                    clearUserDataAndRedirect();
                }
            } else {
                console.error('退出登录请求失败:', response.status);
                clearUserDataAndRedirect();
            }
            
        } catch (error) {
            console.error('退出登录异常:', error);
            clearUserDataAndRedirect();
        } finally {
            // 恢复按钮状态
            const logoutBtn = document.getElementById('logoutBtn');
            if (logoutBtn) {
                logoutBtn.disabled = false;
                logoutBtn.textContent = '退出登录';
                console.log('按钮状态已恢复');
            }
        }
        console.log('=== 退出登录结束 ===');
    }
    
    // 清除用户数据并跳转
    function clearUserDataAndRedirect() {
        console.log('开始清除用户数据并跳转');
        // 清除所有用户相关数据
        localStorage.removeItem('userInfo');
        localStorage.removeItem('userToken');
        console.log('localStorage数据已清除');
        
        // 跳转到登录页
        console.log('准备跳转到登录页');
        window.location.href = 'login.html';
    }

    // 绑定菜单点击事件
    function bindMenu() {
        const menu = document.getElementById('menu');
        if (!menu) {
            console.error('未找到菜单元素！');
            return;
        }

        menu.addEventListener('click', (e) => {
            const btn = e.target.closest('.menu-item');
            if (!btn) return;

            const view = btn.getAttribute('data-view');
            const url = btn.getAttribute('data-url');
            
            console.log('菜单点击:', view, url);
            
            // 根据不同的视图进行页面跳转
            switch (view) {
                case 'schedule':
                    // 跳转到教师课表页面（统一到 /teacher/schedule/）
                    window.location.href = location.origin + '/teacher/schedule/';
                    break;
                case 'password':
                    // 跳转到修改密码
                    window.location.href = location.origin + '/teacher/password/';
                    break;
                case 'students':
                    // 跳转到学生信息
                    window.location.href = location.origin + '/teacher/students/';
                    break;
                case 'upload':
                    // 跳转到上传资料页面（如果存在）
                    console.log('上传资料功能待实现');
                    break;
                case 'download':
                    // 跳转到下载资料页面
                    window.location.href = location.origin + '/teacher/downloadmaterial/';
                    break;
                case 'mymaterials':
                    // 跳转到我的资料页面
                    window.location.href = location.origin + '/teacher/mymaterials/';
                    break;
                case 'feedback':
                    // 课堂反馈入口已移除
                    break;
                
                default:
                    // 默认保持在当前页面（profile）
                    console.log('保持在当前页面');
                    break;
            }
        });
    }

})();
